package com.tool.cn.use.download;

import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 
 * @author wangzonghui
 * @date 2022年4月29日 下午4:29:53 
 * @Description 
 */
public class MainJob {
	
	/**
	 * 下载的文件
	 */
	static String path = "http://softforspeed.51xiazai.cn/down/BaiduNetdisk_6.9.7.4.exe";

	/**
	 * 本地存储文件
	 */
	static String outputFile = "D:/test/BaiduNetdisk_6.9.7.4.exe";
	/**
	 * 线程总数
	 */
    static int threadCount = 3; 
    
    /**
     * 执行完成线程数
     */
    static int finishedThread = 0; 

    public static void main(String[] args) throws Exception {

        URL url  = new URL(MainJob.path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置一些参数
        conn.setRequestMethod("GET");   
        conn.setConnectTimeout(5000);   //设置超时
        conn.setReadTimeout(5000);      //读取超时

        if(conn.getResponseCode()==200){
            //获取总文件大小
            int contentLength = conn.getContentLength();
            //计算各个线程下载数据大小
            int size = contentLength/threadCount;
            
            int tmp=0;
    		if(contentLength>size*threadCount) {
    			tmp=contentLength- threadCount *size;
    		}

            for (int i = 0; i < threadCount; i++) {
                int startIndex = i*size;        // (i从0开始 )
                int endIndex = (i+1)*size;     //结束位置
                
                if(tmp>0&&i==threadCount-1) {
                	endIndex+=tmp;
                }
                
                DownloadThread thread = new DownloadThread(startIndex,endIndex,i);
                thread.start();
            }
        }
    }

}
